package com.zhangmeng.handler;

import cn.hutool.core.io.BufferUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

import java.io.*;
import java.net.Socket;

/**
 * @author zm
 * @date 2025/2/21 15:40
 * @version: 1.0
 */
public class ClientHandler extends Thread {

    private final Log log = LogFactory.get();

    private Socket socket;
    private BufferedReader reader;
    private BufferedWriter writer;
    private OutputStream outputStream;
    private InputStream inputStream;

    public boolean canRun = true;

    public void close() {
        try {
            outputStream.close();
            inputStream.close();
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                // main 线程负责读取客户端发来的信息
                String str = reader.readLine();
                log.info("客户端说：" + str);
                // main 线程负责读取客户端发来的信息
                writer.write("服务器收到消息："  + "\n");
                writer.flush();
            }

        } catch (IOException e) {
            close();
            //throw new RuntimeException(e);
        }

    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public ClientHandler(Socket socket) {
        this.socket = socket;
        try {
            this.inputStream = socket.getInputStream();
            this.outputStream = socket.getOutputStream();
            this.reader = new BufferedReader(new InputStreamReader(inputStream));
//            this.reader = new BufferedReader(new InputStreamReader(System.in));
            this.writer = new BufferedWriter(new OutputStreamWriter(outputStream));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public BufferedReader getReader() {
        return reader;
    }

    public void setReader(BufferedReader reader) {
        this.reader = reader;
    }

    public BufferedWriter getWriter() {
        return writer;
    }

    public void setWriter(BufferedWriter writer) {
        this.writer = writer;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
}
